/**
 * 
 */
package escola.spring.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import escola.logic.usuario.UsuarioLogic;
import escola.modelo.permissao.PermissaoUsuario;
import escola.modelo.usuario.Usuario;

/**
 * @author Jonathan
 *
 */
@Service("hibernateUserDetailsService")
public class HibernateUserDetailsService implements UserDetailsService {
	
	private @Autowired UsuarioLogic userLogic;
	
	@Override
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
		Usuario user = userLogic.getUserByUsername(getUserName(login));
		if (user == null) {
			throw new RuntimeException("Usuário não encontrado.");
		}
		return new User(user.getLogin(), user.getSenha(), true, true, true, true, getAuthorites(user));
	}

	private String getUserName(String login) {
		String[] username = login.split("@"); 
		return username[0];
	}

	private Collection<? extends GrantedAuthority> getAuthorites(Usuario user) {
		List<String> roles = new ArrayList<String>();
		for (PermissaoUsuario role : user.getPermissoes()) {
			roles.add(role.getRole());
		}
		return getGrantedAuthority(roles);
	}

	private Collection<? extends GrantedAuthority> getGrantedAuthority(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String string : roles) {
			authorities.add(new SimpleGrantedAuthority(string));
		}
		return authorities;
	}

}
